<?php
/**
 * Created by PhpStorm.
 * User: Huyang
 * Date: 2016/10/12
 * Time: 11:28
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Repositories\Services\IUser;
use App\Util\ResultsVo;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Config;

class WeChatController extends Controller
{

    public $userService;

    public function __construct(IUser $userService)
    {
        $this->userService = $userService;
    }

    public function sign(Request $request) {

        $url = $request->get('url');

        $config = Config::get('wechat.chat');

        $app = Factory::officialAccount($config);

        if ($url) {
            $app->jssdk->setUrl($url);
        }

        //api, debug, beta, json
        $data = $app->jssdk->buildConfig(['onMenuShareTimeline','onMenuShareAppMessage','scanQRCode'], false, false, false);

        #$data = json_decode((string)$data, true);

        return response()->json(new ResultsVo(['data'=>$data]));

    }

    public function share(Request $request) {

        $url = $request->get('url');

        $config = Config::get('wechat.chat');

        $app = Factory::officialAccount($config);

        if ($url) {
            $app->jssdk->setUrl($url);
        }

        $data = $app->jssdk->buildConfig(['onMenuShareTimeline','onMenuShareAppMessage','hideMenuItems','showMenuItems'], true, false, false);

        #$data = json_decode((string)$data, true);

        return view('www.share', ['data'=>$data]);

    }

    public function oauth() {

        $config = Config::get('wechat.oauth');

        $app = Factory::officialAccount($config);

        $oauth = $app->oauth;

        //此处指定授权方式
        return $oauth->scopes(['snsapi_userinfo'])->redirect();

    }

    public function callback(Request $request) {

        $config = Config::get('wechat.oauth');

        $app = Factory::officialAccount($config);

        $oauth = $app->oauth;

        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();

        $data = $user->getOriginal();

        $token = $this->userService->oauth($request, $data, $request->get('recommendId'));

        if ($request->get('jumpUrl')) {
            if (strpos($request->get('jumpUrl'), '?') === false) {
                Header('Location:'.$request->get('jumpUrl').'?Authorization='.$token);
            } else {
                Header('Location:'.$request->get('jumpUrl').'&Authorization='.$token);
            }
        } else {
            Header('Location:'.getenv('APP_URL').'/index.html?Authorization='.$token);
        }

        Exit;

    }

    public function message() {
        Artisan::call('Progress', [
            'id'=>5, 'progress'=>1
        ]);
    }

}